#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import os

from onvif_ptz.onvif_base import Onvif
from onvif_ptz.path_conf import BASE_DIR


def get_camera_ptz(is_write: bool = False):
    onvif = Onvif()
    try:
        ptz_type = onvif.ptz_service.create_type('GetStatus')
        ptz_type.ProfileToken = onvif.media_service.GetProfiles()[0].token
        res = onvif.ptz_service.GetStatus(ptz_type)
        p = res['Position']['PanTilt']['x']
        t = res['Position']['PanTilt']['y']
        z = res['Position']['Zoom']['x']
    except Exception as e:
        raise RuntimeError(f'获取相机 ptz 失败: {e}')
    else:
        if is_write:
            ptz_json_file = os.path.join(BASE_DIR, 'output_ptz.json')
            ptz_json = {'p': p, 't': t, 'z': z}
            with open(ptz_json_file, encoding='utf-8', mode='w') as jf:
                json.dump(ptz_json, jf)
        else:
            print(f'p: {p}\nt: {t}\nz: {z}')
